import React from "react";
import { useDispatch } from "react-redux";
import useGetComponentInfo from "../../../hooks/useGetComponentInfo";
import useGetPageInfo from "../../../hooks/useGetPageInfo";
import { changeComponentProps } from "../../../store/componentsReducer";
import {
  ComponentPropsType,
  getComponentConfByType,
} from "../../components/QuestionComponents";

const NoProp: React.FC = () => {
  return <div style={{ textAlign: "center" }}>未选中组件</div>;
};

const ComponentProp: React.FC = () => {
  const dispatch = useDispatch();
  const { selectedComponent } = useGetComponentInfo();
  const { isPublished } = useGetPageInfo();
  if (!selectedComponent) return <NoProp />;
  const { type, props, isHidden, isLocked } = selectedComponent;
  const componentConf = getComponentConfByType(type);
  if (!componentConf) return <NoProp />;
  const { PropComponent } = componentConf;

  function changeProps(newProps: ComponentPropsType) {
    if (!selectedComponent) return;
    dispatch(changeComponentProps({ id: selectedComponent.id, newProps }));
  }

  return (
    <PropComponent
      {...props}
      onChange={changeProps}
      disabled={isHidden || isLocked || isPublished}
    />
  );
};

export default ComponentProp;
